package com.tiancy.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


/**
 * 流处理写法统计无界流中数据统计单词频次 . 用 DataStream API做了批处理的实现
 * 基本思路：先逐行读入文件数据，然后将每一行文字拆分成单词；接着按照单词分组，统计每组数据的个数，就是对应单词的频次。
 * 在 hadoop202 上执行 nc -lk 7777
 */
public class Using_3_SocketWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 在hadoop202 上执行命令: nc -lk 7777 模拟无界流数据
        DataStreamSource<String> socketDs = env.socketTextStream("hadoop202", 7777);
        // 不使用 lambda 写法,不会报错
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDs = socketDs.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    Tuple2<String, Integer> wordToOne = Tuple2.of(word, 1);
                    out.collect(wordToOne);
                }
            }
        });
        wordToOneDs.keyBy(0).sum(1).print();
        env.execute();
    }
}